<?php
/**
 * 会员充值
 * @return
 * @author yuncran@126.com
 */

namespace app\api\controller;

use app\BaseController;
use app\model\ConfigModel;
use app\model\GoldLangPackageModel;
use app\model\GoldModel;
use app\model\RechargeGoldModel;
use app\model\UserModel;
use app\Request;
use think\Exception;

class Recharge extends BaseController
{

    /**
     * 升级金币列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author yuncran@126.com
     */
    public function getGoldList()
    {
        $response = GoldModel::getGoldList();
        return $this->renderSuccess($response, lang('查询成功'));
    }


    /**
     * 充值金币
     * @return void
     * @author yuncran@126.com
     */
    public function rechargeGoldList()
    {
        $response = RechargeGoldModel::getRechargeList();
        return $this->renderSuccess($response, lang('查询成功'));
    }


    /**
     * @return void
     * @author yuncran@126.com
     */
    public function getRechargeParam()
    {
        $data = [
            'guid' => $this->request->host() . substr(date('YmdHis') . bin2hex(random_bytes(8)), 0, 32),
            'ip' => $this->request->ip(),
            'url_referrer_domain' => $this->request->host(),
            'mid' => '105',
            'corp' => 'hn8090kj',
        ];
        return $this->renderSuccess($data, lang('查询成功'));
    }

    /**
     * 添加 usdt
     * @return void
     * @author yuncran@126.com
     */
    public function addUsdt()
    {
        $user = UserModel::where('id',$this->uid)->field(['nickname','email'])->find();
        $param = $this->request->param();
        $message = array(
            'money.require' => lang('金额必填'),
        );
        $validate = new \think\Validate();
        $check = $validate->message($message)->check($param,
            [
                'money' => 'require'
            ]
        );
        if (!$check) return $this->renderError($validate->getError());
        $save['order_sn'] = order_no(); //订单号
        $save['user_id'] = $this->uid;
        $save['image'] = $param['image'];
        $save['money'] = $param['money'];
        $save['gold_money'] = isset($param['gold_money']) ? $param['gold_money'] : $param['money'];
        $save['type'] = 3;
        $save['merchant_id'] = $this->merchantId;
        $save['username'] = $user['nickname'];
        $save['email'] = $user['email'];

//        event('DrawLog', [
//            'merchant_id' => $this->merchantId,
//            'user_id' => $this->uid,
//            'money' => $param['money'],
//            'type' => 1,
//            'expend' => 'recharge',
//        ]);

//        $response = \app\model\RechargeUsdtModel::create($save);
        $response = \app\model\RechargeModel::create($save);
        if ($response) {
            return $this->renderSuccess([], lang('充值成功'));
        }
        return $this->renderError(lang('充值失败'));
    }

    /**
     * 获取充值记录
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function getUsdtLog()
    {
        $param = $this->request->param();
        $response = \app\model\RechargeUsdtModel::field(['id', 'order_sn', 'user_id', 'image', 'status', 'create_time'])->order(['id' => 'DESC'])
            ->paginate()->each(function ($item) {
                return $item;
            });
        return $this->renderSuccess($response, lang('查询成功'));
    }

    /**
     * 获取充值币地址
     * @param Request $request
     * @return \think\response\Json
     * @throws \Exception
     * @author yuncran@126.com
     */
    public function getUsdtConfig(Request $request)
    {
//        $qrCode = new  \Endroid\QrCode\QrCode($string); // 需要编码的内容
//        $writer = new  \Endroid\QrCode\Writer\PngWriter;
//        // 生成二维码并保存为文件
//        $result = $writer->write($qrCode);
//        $result->saveToFile('qrcode/qrcode.png'); // 保存到文件
//        if (!$result) {
//            return $this->renderError('操作失败');
//        }
        $data = [
            'usdt_address' => ConfigModel::where('name', 'example_usdt_address')->cache(true, 60)->value('value'),
            'usdt_image' => ConfigModel::where('name', 'example_usdt_image')->cache(true, 60)->value('value'),
        ];
        return $this->renderSuccess($data, lang('查询成功'));
    }


    /**
     * 提交充值信息
     * @return void
     * @author yuncran@126.com
     */
    public function addRecharge()
    {
        $param = $this->request->param();
        $message = array(
            'username.require' => lang('会员名称必填'),
            'username.min' => lang('会员名称长度不能小于1个字符'),
            'username.max' => lang('会员名称长度在1~15个字符'),
            'email.require' => lang('会员邮箱必填'),
        );
        $validate = new \think\Validate();
        $check = $validate->message($message)->check($param,
            [
                'username' => 'require|min:1|max:15', 'email' => 'require|email',
            ]
        );
        if (!$check) return $this->renderError($validate->getError());

        $data = array_merge([
            'user_id' => $this->uid,
            'money' => $param['money'],
            'gold_money' => isset($param['gold_money']) ? $param['gold_money'] : $param['money'],
            'create_time' => date('Y-m-d H:i:s', time()),
        ], $param);

        $price_currency = 'USD';
        $money = $param['money'];
        $phone = $param['phone'];
        $merchant_id = ConfigModel::where('name', 'example_visa_app_id')->value('value');

        $gold_money = $data['gold_money'];
        $merch_order_id = order_no(); //订单号
//        $order_hash = 'SkKCUlfRiQxtajoRpPACePhloARbzirFAabg4QG3kfpVrXvd5Hj3hh2cdyotCer8y128hiWHjGs7zu3zeNe18xxsg7cFCmAgXqxz4v5XUKUKX3MREXpX8z8bDJ2ifrf5';
        $order_hash = ConfigModel::where('name', 'example_visa_hash')->value('value');

        $signature = md5($order_hash . $merchant_id . $merch_order_id . $price_currency . $money);
//        $url_sync = $this->request->root(true) . '/api/Cropay/callback?orderid=' . $merch_order_id;
//        $url_back = $this->request->root(true) . '/api/cropay/urlback?orderid=' . $merch_order_id;
        $url_sync = $this->request->root(true) . '/Home/callUrl?orderid=' . $merch_order_id;
        $url_back = $this->request->root(true) . '/Home/callBack?orderid=' . $merch_order_id;
        $merchant_id_mm = $merchant_id * 818 + 5201314;

        $data = [
            'merchant_id' => $merchant_id_mm, //商户号
            'order_type' => 3,
            'gw_version' => 'php(1.0)',
            'language' => 'en-us',
            'merch_order_ori_id' => uniqid(),
            'merch_order_id' => $merch_order_id,
            'merch_order_date' => date('YmdHis'),
            'price_currency' => $price_currency, // 币种
            'price_amount' => $money, // 金额
            'ip' => $this->request->ip(),
            'url_sync' => $url_sync,
            'url_succ_back' => $url_back,
            'url_fail_back' => $url_back,
            'url_referrer_domain' => $this->request->host(),//域名
            'order_remark' => 'user recharge',
            'bill_email' => $data['email'], //邮箱
            'bill_phone' => $phone, //手机号
            'delivery_name' => $param['username'], //姓名
            'delivery_email' => $data['email'], //邮箱
            'delivery_phone' => $phone, //手机号
            'product_name' => 'Recharge', //商品名称
            'product_sn' => uniqid(), //商品货架号
            'quantity' => 1,
            'unit' => $money,  // 单价
            'guid' => $this->request->host() . substr(date('YmdHis') . bin2hex(random_bytes(8)), 0, 32),
            'signature' => $signature, //签名
        ];
        try {
            $url = 'https://gateway.sslonlinepay.com/Api/payOrder.aspx';
            $response = $this->httpRequest($url, 'POST', $data);
        } catch (Exception $exception) {
            return $this->renderError(lang('充值失败'));
        }
        $result = simplexml_load_string($response);

        $save['order_sn'] = $merch_order_id;
        $save['user_id'] = $this->uid;
        $save['username'] = $param['username'];
        $save['phone'] = $param['phone'];
        $save['email'] = $param['email'];
        $save['type'] = $param['type'];
        $save['money'] = $money;
        $save['gold_money'] = $gold_money;
        $save['merchant_id'] = $this->merchantId;
        $response = \app\model\RechargeModel::create($save);

        //充值消耗拿提成
//        event('DrawLog', [
//            'merchant_id' => $this->merchantId,
//            'user_id' => $this->uid,
//            'money' => $money,
//            'type' => 1,
//            'expend' => 'recharge',
//        ]);

        $result->payment_url = !empty($result->payment_url) ? base64_decode($result->payment_url) : '';
        if (!$response) return $this->renderError(lang('充值失败'));
        return $this->renderSuccess($result, lang('请求成功'));
    }

    /** 请求方法 必须参考该方法  */
    public function httpRequest($url, $method = "GET", $post_fields = null, $product = array(), $headers = array())
    {
        $method = strtoupper($method);//转为数据
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT']); // 在HTTP请求中包含一个’user-agent’头的字符串。
        curl_setopt($ci, CURLOPT_REFERER, $_SERVER ['HTTP_HOST']); // 在HTTP请求中包含一个’referer’头的字符串。
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 3000); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                $tmp_data_str = '';
                if (!empty($post_fields)) {
                    $tmp_data_str .= is_array($post_fields) ? http_build_query($post_fields) : $post_fields;
                }
                if (!empty($product)) {
                    for ($i = 0; $i < count($product); $i++) {
                        foreach ($product[$i] as $key => $val) {
                            $tmp_data_str .= "&" . $key . "=" . $val;
                        }
                    }
                }
                $str_data = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $tmp_data_str);
                curl_setopt($ci, CURLOPT_POSTFIELDS, $str_data);
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ci, CURLOPT_HEADER, 0);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        $response = curl_exec($ci);

        //返回结果
        if ($response) {
            curl_close($ci);
            return $response;
        } else {
            $error = curl_errno($ci);
            $msg = curl_error($ci);
            curl_close($ci);
            throw new \Exception("curl出错，错误码:$error,错误原因是:$msg");
        }
    }

    //旧版本
    public function addRechargeOldCopy()
    {
        $param = $this->request->param();
        $message = array(
            'username.require' => lang('会员名称必填'),
            'username.min' => lang('会员名称长度不能小于1个字符'),
            'username.max' => lang('会员名称长度在1~15个字符'),
            'email.require' => lang('会员邮箱必填'),
            'gold_id.require' => lang('gold_id必填'),
        );
        $validate = new \think\Validate();
        $check = $validate->message($message)->check($param,
            [
                'username' => 'require|min:1|max:15', 'email' => 'require|email', 'gold_id' => 'require',
            ]
        );
        if (!$check) return $this->renderError($validate->getError());
        $gold = GoldModel::getOne(['id' => $param['gold_id']]);
        if (empty($gold)) {
            return $this->renderError(lang('为找到相关金币信息'));
        }
        $data = array_merge([
            'user_id' => $this->uid,
            'money' => $gold['money'],
            'gold_money' => $gold['gold_money'],
            'create_time' => date('Y-m-d H:i:s', time()),
        ], $param);
        unset($data['gold_id']);
        $response = \app\model\RechargeModel::create($data);
        if (!$response) return $this->renderError(lang('充值失败'));
        return $this->renderSuccess($response, lang('充值成功'));
    }

    /**
     * 获取会员充值记录
     * @return void
     * @author yuncran@126.com
     */
    public function getRechargeListLog()
    {
        $response = \app\model\RechargeModel::where('user_id', $this->uid)
            ->order(['id' => 'DESC'])
            ->paginate()->each(function ($item) {
                $list = ['0' => lang('待支付'), '1' => lang('充值成功'), '2' => lang('充值失败')];
                $item['status_txt'] = $list[$item['status']] ?? lang('未知');
                if ($item['type'] == 3) {
                    $list = ['0' => lang('待审核'), '1' => lang('已审核'), '2' => lang('已驳回')];
                    $item['status_txt'] = $list[$item['examine_status']] ?? lang('未知');
                }
                return $item;
            });
        return $this->renderSuccess($response, lang('查询成功'));
    }


    /**
     * 获取会员语言翻译包
     * @return void
     * @author yuncran@126.com
     */
    public function getGoldLangPackage()
    {
        $response = GoldLangPackageModel::getGoldLangPackageList();
        return $this->renderSuccess($response, lang('查询成功'));
    }


}